package com.iwunu.gateway.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.iwunu.gateway.cache.RedisService;
import com.iwunu.gateway.constant.ApartmentConstant;
import com.iwunu.gateway.entity.FaceLock;
import com.iwunu.gateway.service.CmdIssuedMongodbService;
import com.iwunu.gateway.service.FaceLockMemberService;
import com.iwunu.gateway.service.FaceLockService;
import com.iwunu.gateway.service.ImageMongodbService;
import com.iwunu.gateway.service.TokenService;
import com.iwunu.gateway.vo.FaceLockVo;
import com.iwunu.gateway.vo.LockUpdateVo;
import com.iwunu.iot.common.constant.ClientOpenTypeEnum;
import com.iwunu.iot.common.constant.ResultCodeEnum;
import com.iwunu.iot.common.util.DESUtil;
import com.iwunu.iot.common.util.Result;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

@RestController
@Api(value = "lock/member", tags = "人脸锁控制层接口", description = "人脸锁接口")
public class OrgFacesLockController {
    @Autowired
    public RedisService  redisService;
    @Autowired
    public FaceLockService faceLockService;
    @Autowired
    public FaceLockMemberService faceLockMemberService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ImageMongodbService imageMongodbService;
    @Autowired
    private CmdIssuedMongodbService cmdIssuedMongodbService;
	@RequestMapping(value = "/org/bind" , method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> addFaceLock(
    		 @RequestHeader String Authorization,
    		@RequestBody FaceLockVo faceLockVo
    		){
    	 Result result = null ;
    	 String userId = tokenService.parseOrgToken(Authorization);
         String mac = faceLockVo.getBaseCode().replace(":", "");
    	  String clientId = mac.substring(mac.length()-4,mac.length()).toUpperCase();
    	if(faceLockVo==null || !StringUtils.isNoneEmpty(faceLockVo.getClientId())) {
    		 result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(),null);
           	 return new ResponseEntity<>(result, HttpStatus.OK);	
    	}
    	
    	String user =  DESUtil.encryptString("user");
    	if(clientId.contains(user)) {
    		clientId = clientId.replace(user, "");
    		
    	}
	
    	if(faceLockService.getFaceLockByMac(clientId)!=null) {
	   		 result = new Result(ResultCodeEnum.DEVICE_EIXT.getCode(), ResultCodeEnum.DEVICE_EIXT.getDesc(),null);
	       	 return new ResponseEntity<>(result, HttpStatus.OK);	
    	}
    	 faceLockVo.setClientId(clientId);
    	 faceLockService.save(faceLockVo, userId);
  		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),null);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
    
	@RequestMapping(value = "/org/updateLock/{lockId}" , method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> updateLock(
    		@RequestHeader String Authorization,
    		@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId,
    		@RequestBody LockUpdateVo fl
    		){
    	 Result result = null ;
    	 FaceLock  flock = faceLockService.update(fl,lockId);
  		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),flock);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
	
	@RequestMapping(value = "/org/del/{lockId}" , method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> delFaceLock(
    		@RequestHeader String Authorization,
    		@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId
    		){
    	Result result = null ;
     	 String imageType =  ClientOpenTypeEnum.DELFACES.getData();
      	 String pwdType =  ClientOpenTypeEnum.DELPWD.getData();
    	FaceLock fl =faceLockService.getFaceLockByUUID(Long.valueOf(lockId));
    	if(fl==null) {
	   		 result = new Result(ResultCodeEnum.NOT_GATEWAY.getCode(), ResultCodeEnum.NOT_GATEWAY.getDesc(),null);
	       	 return new ResponseEntity<>(result, HttpStatus.OK);	
    	}
        String imagekey = fl.getClientId()+imageType;
        String pwdkey = fl.getClientId()+pwdType;
        redisService.rightPush(imagekey,"50");
        redisService.rightPush(pwdkey, "100");
 		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),null);
       	return new ResponseEntity<>(result, HttpStatus.OK);
    }
	/**
	 **获取锁二维码
	 * @param Authorization
	 * @param lockId
	 * @return
	 */
	@RequestMapping(value = "/org/getCode/{lockId}" , method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> getCode(
    		@RequestHeader String Authorization,
    		@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId
    		){
    	Result result = null ;
    	FaceLock fl =faceLockService.getFaceLockByUUID(Long.valueOf(lockId));
    	if(fl==null) {
	   		 result = new Result(ResultCodeEnum.GATEWAY_EIXT.getCode(), ResultCodeEnum.GATEWAY_EIXT.getDesc(),null);
	       	 return new ResponseEntity<>(result, HttpStatus.OK);	
    	}
    	JSONObject codeJson = new JSONObject();
    	codeJson.put("lockId", lockId);
    	codeJson.put("lockClientId", fl.getClientId());
    	String menber =  DESUtil.encryptString("menber");
    	String codeString = DESUtil.encryptString(codeJson.toJSONString());
 		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),menber+codeString);
       	return new ResponseEntity<>(result, HttpStatus.OK);
    }
    /**
     * *锁列表
     * @param Authorization
     * @return
     */
	@RequestMapping(value = "/org/lockList" , method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> lockList(
    		@RequestHeader String Authorization
    		){
    	Result result = null ;
    	String userId = tokenService.parseOrgToken(Authorization);
    	 List<Map<String, Object>> lockList = faceLockMemberService.selectByUserFaceLocks(Integer.valueOf(userId));
 		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),lockList);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
    /**
     * *我的锁列表
     * @param Authorization
     * @return
     */
	@RequestMapping(value = "/org/mylockList" , method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> mylockList(
    		@RequestHeader String Authorization
    		){
    	Result result = null ;
    	String userId = tokenService.parseOrgToken(Authorization);
    	 List<Map<String, Object>> lockList = faceLockMemberService.selectMyFaceLocks(Integer.valueOf(userId));
 		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),lockList);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
    /**
     ** 锁详情
     * @param Authorization
     * @param lockerMemberId
     * @return
     */
	@RequestMapping(value = "/org/lockInfo/{lockId}" , method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> lockInfo(
    		@RequestHeader String Authorization,
    		@ApiParam(value = "锁ID", required = true) @PathVariable("lockId") Integer lockId
    		){
    	Result result = null ;
    	String userId = tokenService.parseOrgToken(Authorization);
    	Map<String, Object> lockInfo = faceLockMemberService.findLockInfo(Integer.valueOf(userId), lockId);
 		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),lockInfo);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
    /**
     ** 锁详情
     * @param Authorization
     * @param lockerMemberId
     * @return
     */
	@RequestMapping(value = "/org/getlockByCode" , method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> getlockByCode(
    		@RequestHeader String Authorization,
    		@RequestBody JSONObject json
    		){
    	Result result = null ;
    	
    	String codeString =json.getString("code");
    	String member = DESUtil.encryptString("menber");
    	String user = DESUtil.encryptString("user");
    	String code = codeString.replace(member, "").replace(user, "");
    	JSONObject codeJson = JSONObject.parseObject(DESUtil.decryptString(code));
    	FaceLock fl = faceLockService.getFaceLockByUUID(codeJson.getLong("lockId"));
 		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),fl);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
    /**
     ** 转换成员
     * @param Authorization
     * @param lockerMemberId
     * @return
     */
	@RequestMapping(value = "/org/changeMember/{receiveId}" , method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> changeMember(
    		@RequestHeader String Authorization,
    		@ApiParam(value = "锁取人ID", required = true) @PathVariable("receiveId") Integer receiveId,
    		@RequestBody JSONObject lockIds
    		){
    	Result result = null ;
    	String[] arr = lockIds.getString("lockIds").split(",");
    	List<String> list = Arrays.asList(arr);
    	List<Integer> lockIdArray = new ArrayList<Integer>();
    	for(String lockId :list) {
    		lockIdArray.add(Integer.valueOf(lockId));
    		FaceLock flock = faceLockService.getFaceLockByUUID(Long.valueOf(lockId));
    		String typepwd =  ClientOpenTypeEnum.DELPWD.getData();
         	String typecard =  ClientOpenTypeEnum.DELCARD.getData();
         	String typefingle =  ClientOpenTypeEnum.DELFINGER.getData();
         	String typefaces =  ClientOpenTypeEnum.DELFACES.getData();
            String key = flock.getClientId()+typepwd;
            redisService.rightPush(key,ApartmentConstant.pitNum.toString());
            String  cardkey = flock.getClientId()+typecard;
            redisService.rightPush(cardkey,ApartmentConstant.pitNum.toString());
            String finglekey = flock.getClientId()+typefingle;
            redisService.rightPush(finglekey, ApartmentConstant.pitNum.toString());
            String faceskey = flock.getClientId()+typefaces;
            redisService.rightPush(faceskey,ApartmentConstant.imagePitNum.toString());
    	}
     	
//    	faceLockMemberService.changeMember(lockIdArray,receiveId);
    	faceLockMemberService.delByLockIds(lockIdArray);
 		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),null);
       	return new ResponseEntity<>(result, HttpStatus.OK);
    }
	public static void main(String[] args) {
		String codeString = DESUtil.encryptString("menber");
		String codeString1 = DESUtil.encryptString("user");
	}
}
